package com.sxt.pro.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxt.pro.pojo.Bank;
import com.sxt.pro.pojo.WaterFall;
import com.sxt.pro.service.BankService;
import com.sxt.pro.service.WaterFallService;
import com.sxt.pro.vo.WaterFallVo;
import com.sxt.sys.common.AppFileUtils;
import com.sxt.sys.common.Constast;
import com.sxt.sys.common.DataGridView;
import com.sxt.sys.common.ResultObj;
import com.sxt.sys.common.TreeNode;
import com.sxt.sys.common.WebUtils;
import com.sxt.sys.domain.Terminal;
import com.sxt.sys.service.TerminalService;


/**  

* @Description: 互动营销控制层

* @author xinxiaokang  

* @date 2020年10月22日 下午2:02:24

*/
@RestController
@RequestMapping("/waterFall")
public class WaterFallController {

	@Autowired
	private WaterFallService waterFallService;
	//网点机构
	@Autowired
	private BankService bankService;
	//设备业务层
	@Autowired
	private TerminalService terminalService;
	
	/**
	 * 查询营销产品及分页列表
	 * @param waterFallVo
	 * @return
	 */
	@RequestMapping("/loadAllWaterFall")
	public DataGridView loadAllWaterFall(WaterFallVo waterFallVo){
		//存入网点编号和用户名放入session中
		 int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
		 waterFallVo.setBanknbr(banknbr);
		//获取该网点 子孙 网点id
		List<Integer> bankIds = this.loadTreeJson(banknbr);
		
		//初始化 当前页、每页显示条数
		IPage<WaterFall> page = new Page<>(waterFallVo.getPage(), waterFallVo.getLimit());
		//封装对象查询条件
		QueryWrapper<WaterFall> queryWrapper = new QueryWrapper<WaterFall>();
		//筛选条件：网点编号集合
		queryWrapper.in("banknbr", bankIds);
//		queryWrapper.eq(waterFallVo.getBanknbr()!=null&&waterFallVo.getBanknbr()!=0,"banknbr",waterFallVo.getBanknbr());
		//筛选条件:名称
		queryWrapper.like(StringUtils.isNotBlank(waterFallVo.getWaterbusinessname()), "waterbusinessname", waterFallVo.getWaterbusinessname());
		//筛选条件：大于开始时间
		queryWrapper.ge(waterFallVo.getStartTime()!=null, "creattime", waterFallVo.getStartTime());
		//筛选条件：小于结束时间
		queryWrapper.le(waterFallVo.getEndTime()!=null, "creattime", waterFallVo.getEndTime());
		queryWrapper.orderByDesc("creattime");
		//获取分页数据
		this.waterFallService.page(page, queryWrapper);
		return new DataGridView(page.getTotal(), page.getRecords());
	}
	
	/**
	 * 添加营销产品
	 * @param waterFallVo
	 * @return
	 */
	/**
	 * @param waterFallVo
	 * @return
	 */
	@RequestMapping("addWaterFall")
	public ResultObj addWaterFall(WaterFallVo waterFallVo) {
		//添加时，网点默认
		int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
		waterFallVo.setBanknbr(banknbr);
		try {
			if(waterFallVo.getWaterbusiness()!=null&&waterFallVo.getWaterbusiness().endsWith("_temp")) {
				//封面
				String newName= AppFileUtils.renameFile(waterFallVo.getWaterbusiness());
				waterFallVo.setWaterbusiness(newName);
				waterFallVo.setCreattime(new Date());
			}
			if(waterFallVo.getWaterbusinessimage()!=null&&waterFallVo.getWaterbusinessimage().endsWith("_temp")) {
				//标志
				String newName= AppFileUtils.renameFile(waterFallVo.getWaterbusinessimage());
				waterFallVo.setWaterbusinessimage(newName);
			}
			if(waterFallVo.getWatercodeimage()!=null&&waterFallVo.getWatercodeimage().endsWith("_temp")) {
				//二维码图片
				String newName= AppFileUtils.renameFile(waterFallVo.getWatercodeimage());
				waterFallVo.setWatercodeimage(newName);
			}
			
			/** 批量添加操作  **/
			String ids = "";    //批量添加的id集合
			String terminalNbr = waterFallVo.getBankordevice();  //批量的设备编号
			String[] numbers = terminalNbr.split(",", 0);      //按“，”号分割后的数据
			for (String s : numbers) {
				//封装对象查询条件
				QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
				//筛选条件：设备编号
				queryWrapper .eq(s!=null,"terminal_no",s);
				Terminal terminal = this.terminalService.getOne(queryWrapper);
				waterFallVo.setTerminalno(terminal.getTerminalno());        //赋值设备编号
				waterFallVo.setBanknbr(terminal.getNetworkid());            //赋值网点编号
				this.waterFallService.save(waterFallVo);
				//获取添加的id
				int id = this.waterFallService.saveToId();
					ids +=id+","; 
			}
			
			//批量修改把 主键id集合赋值
			String[] zhids = ids.split(",", 0);      //按“，”号分割后的数据
			for (String zhs : zhids) {
				//封装对象查询条件
				UpdateWrapper<WaterFall> updateWrapper = new UpdateWrapper<>();
				 updateWrapper.eq("id",Integer.parseInt(zhs));     //赋值主键id
				 updateWrapper.set("listid", ids);     //赋值主键集合id
				this.waterFallService.update(updateWrapper);
			}
			return ResultObj.ADD_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.ADD_ERROR;
		}
	}

	/**
	 * 修改营销产品
	 * @param waterFallVo
	 * @return
	 */
	@RequestMapping("updateWaterFall")
	public ResultObj updateWaterFall(WaterFallVo waterFallVo) {
		try {
			//说明是不默认图片
			if(!(waterFallVo.getWaterbusiness()!=null&&waterFallVo.getWaterbusiness().equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
				if(waterFallVo.getWaterbusiness().endsWith("_temp")) {
					String newName= AppFileUtils.renameFile(waterFallVo.getWaterbusiness());
					waterFallVo.setWaterbusiness(newName);
					//删除原先的图片
					String oldPath=this.waterFallService.getById(waterFallVo.getId()).getWaterbusiness();
					if (!(oldPath.equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
						AppFileUtils.removeFileByPath(oldPath);
					}
				}
			}
			if(!(waterFallVo.getWaterbusinessimage()!=null&&waterFallVo.getWaterbusinessimage().equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
				if(waterFallVo.getWaterbusinessimage().endsWith("_temp")) {
					String newName= AppFileUtils.renameFile(waterFallVo.getWaterbusinessimage());
					waterFallVo.setWaterbusinessimage(newName);
					String oldPath=this.waterFallService.getById(waterFallVo.getId()).getWaterbusinessimage();
					if (!(oldPath.equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
						AppFileUtils.removeFileByPath(oldPath);
					}
				}
			}
			if(!(waterFallVo.getWatercodeimage()!=null&&waterFallVo.getWatercodeimage().equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
				if(waterFallVo.getWatercodeimage().endsWith("_temp")) {
					String newName= AppFileUtils.renameFile(waterFallVo.getWatercodeimage());
					waterFallVo.setWatercodeimage(newName);
					String oldPath=this.waterFallService.getById(waterFallVo.getId()).getWatercodeimage();
					if (!(oldPath.equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
						AppFileUtils.removeFileByPath(oldPath);
					}
				}
			}
			
			/** 批量修改操作  **/
			String ids = waterFallVo.getListid();  //批量的主键id集合
			String[] numbers = ids.split(",", 0);      //按“，”号分割后的数据
			for (String s : numbers) {
				waterFallVo.setId(Integer.parseInt(s));    //赋值主键id
				this.waterFallService.updateById(waterFallVo);
			}
			return ResultObj.UPDATE_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.UPDATE_ERROR;
		}
	}

	/**
	 * 批量删除/删除
	 * @param id
	 * @param listid   主键集合
	 * @param waterbusiness
	 * @param waterbusinessimage
	 * @param watercodeimage
	 * @return
	 */
	@RequestMapping("deleteWaterFall")
	public ResultObj deleteWaterFall(Integer id,String listid,String waterbusiness,
			String waterbusinessimage,String watercodeimage) {
		try {
			/** 批量删除操作  **/
			if(!listid.isEmpty()){
				String[] numbers = listid.split(",", 0);      //按“，”号分割后的数据
				for (String s : numbers) {
					this.waterFallService.removeById(Integer.parseInt(s));
				}
				//删除原文件
				if (!waterbusiness.isEmpty() && !waterbusiness.equals("images/defaultgoodsimg.png")) {
					AppFileUtils.removeFileByPath(waterbusiness);
				}
				if (!waterbusinessimage.isEmpty() && !waterbusinessimage.equals("images/defaultgoodsimg.png")) {
					AppFileUtils.removeFileByPath(waterbusinessimage);
				}
				if (!watercodeimage.isEmpty() && !watercodeimage.equals("images/defaultgoodsimg.png")) {
					AppFileUtils.removeFileByPath(watercodeimage);
				}
				return ResultObj.DELETE_SUCCESS;
			}else{
				return ResultObj.DELETE_ERR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.DELETE_ERROR;
		}
	}
	
	/**
	 * 加载网点管理树的json
	 * @return 
	 */
	@RequestMapping("loadTreeJson")
	public DataGridView loadTreeJsonS() {
		int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
//		int banknbr = 103;
		//获取该网点 子孙 网点id
		List<Integer> bankIds = this.loadTreeJson(banknbr);
		List<TreeNode> treeNodes= new ArrayList<>();
		for (int i = 0; i < bankIds.size(); i++) {
			//封装对象查询条件
			QueryWrapper<Bank> queryWrapperA = new QueryWrapper<Bank>();
			//筛选条件：网点编号是主键id 或者 是父 级id
			queryWrapperA .eq(banknbr!=0,"dept_id",bankIds.get(i));
			Bank bankA = this.bankService.getOne(queryWrapperA);
			if(bankIds.get(i)== banknbr){
				bankA.setParentid(0);
			}
//			Boolean spread=true;
			treeNodes.add(new TreeNode(bankA.getId(), bankA.getParentid(), bankA.getDeptname(), false,true));
			
			//获取网点下设备
			QueryWrapper<Terminal> queryWrapper=new QueryWrapper<>();
			//筛选条件：网点编号
			 queryWrapper.eq(bankIds.get(i)!=0,"network_id",bankIds.get(i));
			 List<Terminal> list = this.terminalService.list(queryWrapper);
			 if (list.size()>0) {
				 for (Terminal ter:list){
					 treeNodes.add(new TreeNode((int)((Math.random()*9+1)*1000), bankIds.get(i), ter.getTerminalno(), false,false));
				}
			}
		}
			return new DataGridView(treeNodes);
	}
	
	
	/**
	 * 递归根据节点id 获取其子孙id
	 */
	private List<Integer> childrenWithIds = new ArrayList<>();
	//根据父节点获取全部子节点
    public  List<Integer>  loadTreeJson(Integer id){
    	this.childrenWithIds.clear();
    	//递归算 下级分行树数据
		List<Bank> list = this.bankService.list();
		List<Integer> listA = recursionGetIds(list, id);
		listA.add(id);
		return listA;
    }
	
	//递归方法获取子节点
    public  List<Integer>  recursionGetIds(List<Bank> list,Integer id){
    	for (Bank p:list){
			if (p.getParentid().equals(id)){
				recursionGetIds(list, p.getId());
				childrenWithIds.add(p.getId());
			}
		}
		return childrenWithIds;
    }
	
	
	
	
	
	
	
}
